package com.linjj.seckill.service.impl;

import com.linjj.seckill.domain.Order;
import com.linjj.seckill.domain.SeckillOrder;
import com.linjj.seckill.domain.User;
import com.linjj.seckill.redis.RedisService;
import com.linjj.seckill.redis.SeckillKey;
import com.linjj.seckill.service.IGoodsService;
import com.linjj.seckill.service.IOrderService;
import com.linjj.seckill.service.ISeckillService;
import com.linjj.seckill.vo.SeckillGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Service
public class SeckillService implements ISeckillService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;
    private static char[] ops = new char[] {'+', '-', '*'};
    /**
     * 秒杀商品
     * 减库存成功->创建订单
     * 减库存失败->秒杀结束,setGoodsOver
     * */
    @Override
    @Transactional
    public Order seckill(User user, SeckillGoodsVo seckillVo,String address) {
        boolean success = goodsService.reduceStock(seckillVo.getId());
        if(success){
            Order order = orderService.createOrder(user,seckillVo,address);
            return order;
        }else{
            setGoodsOver(seckillVo.getId());//秒杀结束
            return null;
        }
    }
    /**
     * 生成图片验证码
     * 使用Graphics绘画干扰点和表达式
     * */
    @Override
    public BufferedImage createVerifyCode(User user, long goodsId) {
        if(user == null || goodsId <=0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        redisService.set(SeckillKey.seckillVerifyCode, user.getUserId()+"_"+goodsId, rnd);
        //输出图片
        return image;
    }
    /**
     * 生成随机计算表达式
     * */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = ""+ num1 + op1 + num2 + op2 + num3;
        return exp;
    }
    /**
     * 使用JavaScript引擎计算表达式
     * */
    private int calc(String verifyCode) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer)engine.eval(verifyCode);
        }catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 检查用户提交的计算结果
     * 删除redis缓存的正确结果
     * */
    @Override
    public boolean checkVerifyCode(User user, long goodsId, int verifyCode) {
        Integer code = redisService.get(SeckillKey.seckillVerifyCode, user.getUserId()+"_"+goodsId,int.class);
        if(code == null || code-verifyCode!=0){
            return false;
        }
        redisService.delete(SeckillKey.seckillVerifyCode, user.getUserId()+"_"+goodsId);
        return true;
    }

    /**
     * 轮询秒杀结果
     * 查询订单成功->秒杀成功
     * 查询订单失败->getGoodsOver？-1:0
     * -1：秒杀结束
     * 0：排队中
     * */
    @Override
    public long getSeckillResult(long userId, long goodsId) {
        SeckillOrder order = orderService.getSeckillOrderByUserIdAndGoodsId(userId, goodsId);
        if(order != null) {//秒杀成功
            return order.getOrderId();
        }else {
            boolean isOver = getGoodsOver(goodsId);
            return isOver?-1:0;
        }
    }

    /**
     * 设置秒杀结束标志
     * */
    private void setGoodsOver(Long goodsId) {
        redisService.set(SeckillKey.isSeckillOver, ""+goodsId, true);
    }
    /**
     * 获取秒杀结束标志
     * true:秒杀结束
     * false：秒杀未结束
     * */
    private boolean getGoodsOver(long goodsId) {
        return redisService.exists(SeckillKey.isSeckillOver, ""+goodsId);
    }
}
